package com.hirsi.common.core.validator;

import cn.hutool.core.collection.CollUtil;
import com.hirsi.common.core.enums.IVoEnum;
import com.hirsi.common.core.validator.annotation.EnumValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;


public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private List<Object> values;

    private boolean ignoreNull;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        this.values = new ArrayList<>();
        this.ignoreNull = constraintAnnotation.ignoreNull();
        Class<? extends IVoEnum> clazz = constraintAnnotation.value();
        IVoEnum[] voEnums = clazz.getEnumConstants();
        if (voEnums == null || voEnums.length == 0) return;
        for (IVoEnum voEnum : voEnums) {
            values.add(voEnum.getValue());
        }
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        if ((o == null && ignoreNull) || (CollUtil.isNotEmpty(values) && values.contains(o))) return true;
        return false;
    }
}
